package main

import (
	"bytes"
	"golang.org/x/text/encoding/simplifiedchinese"
	"log"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
	"syscall"
)

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func openFooModel(m *FooModel, s string, mv MyMainWindow) {
	date := getDate(s)
	list := make([]*Foo, 0)
	for i := 1; i <= len(date); i++ {
		foo := date[i-1]
		foo.Index = i
		split := strings.Split(foo.address, ":")

		if s == split[len(split)-1] {
			foo.port = split[len(split)-1]
			list = append(list, foo)
		}
	}
	println(len(list))
	m.items = list
	m.PublishRowsReset()
}

func killPort(f *Foo) {
	//taskkill /pid "+p+" -t -f
	var stdout bytes.Buffer
	s := "taskkill /pid " + f.pid + " -t -f"
	cmd := exec.Command("cmd", "/C", s)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}

	cmd.Stdout = &stdout
	err := cmd.Run()
	if err != nil {
		log.Println("killPort失败:", err)
	}
}

func getDate(s string) []*Foo {
	var stdout bytes.Buffer
	cmd := exec.Command("cmd", "/C", "netstat -aon|findstr "+s)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	cmd.Stdout = &stdout
	err := cmd.Run()
	if err != nil {
		log.Println("启动失败:", err)
		return make([]*Foo, 0)
	}
	s1 := ConvertByte2String(stdout.Bytes(), "GB18030")
	a := strings.Split(s1, "\r")

	list := make([]*Foo, 0)
	listString := make([]string, 0)
	//正则替换空格
	reg := regexp.MustCompile(`[\s]{1,}`)
	for i := 0; i < len(a); i++ {
		v := a[i]
		v = reg.ReplaceAllString(v, " ")
		v = strings.Replace(v, "\r", "", -1)
		v = strings.Replace(v, "\n", "", -1)
		a1 := strings.Split(v, " ")
		if len(a1) < 5 {
			continue
		}
		if len(a1) == 5 {
			a2:= make([]string,6)
			a2[0]=a1[0]
			a2[1]=a1[1]
			a2[2]=a1[2]
			a2[3]=a1[3]
			a2[4]=""
			a2[5]=a1[4]
			a1=a2
		}
		foo01 := &Foo{
			//0是空格
			agr:     a1[1],
			address: a1[2],
			outAddress: a1[3],
			pid:     a1[5],
			state:   a1[4],
		}

		listString = append(listString, a1[5])
		list = append(list, foo01)
	}


	for i := 0; i < len(list); i++ {
		foo := list[i]
		var pid = foo.pid
		cmdList := getCmdList("tasklist |findstr " + pid)
		if len(cmdList) != 0 {
			i2 := cmdList[0]
			foo.serviceName = i2[0]
			i2[4] = strings.Replace(i2[4], ",", "", -1)
			atoi, err := strconv.Atoi(i2[4])
			mo := ""
			if err != nil {
				mo = i2[4] + " k"
			} else {
				atoi = atoi / 1024
				if atoi > 1024 {
					atoi = atoi / 1024
					mo = strconv.Itoa(atoi) + " G"
				} else {
					mo = strconv.Itoa(atoi) + " m"
				}
			}
			foo.memory = mo
		}
	}

	return list

}

func getCmdList(ml string) [][]string {
	var stdout bytes.Buffer
	cmd := exec.Command("cmd", "/C", ml)
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	result := make([][]string, 0)
	cmd.Stdout = &stdout
	err := cmd.Run()
	if err != nil {
		log.Println("查询端口失败:", err)
	}
	s1 := ConvertByte2String(stdout.Bytes(), "GB18030")
	s1 = strings.Replace(s1, "\n", "", -1)
	a := strings.Split(s1, "\r")
	//正则替换空格
	reg := regexp.MustCompile(`[\s]{1,}`)
	for i := 0; i < len(a); i++ {
		data := a[i]
		if len(data) == 0 {
			continue
		}
		data = reg.ReplaceAllString(data, " ")
		data = strings.Replace(data, "\r", "", -1)
		data = strings.Replace(data, "\n", "", -1)
		a1 := strings.Split(data, " ")
		//fmt.Println(a1)
		result = append(result, a1)
	}

	return result
}

func ConvertByte2String(byte []byte, charset Charset) string {
	var str string
	switch charset {
	case GB18030:
		var decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}
	return str
}

func IsContainStr(items []string, item string) bool {
	for _, eachItem := range items {
		if eachItem == item {
			return true
		}
	}
	return false
}
